<?php

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\User\UserDao;
use App\Http\Repositories\Redis\UserRedis;
use App\Http\Requests\UserContext;
use App\Models\TeamUser;


class UserCenterService extends BaseService
{
    protected $userDao;

    public function __construct(UserDao $userDao)
    {
        $this->userDao = $userDao;
    }

    public function userInfo(UserContext $userContext)
    {
        $userId = $userContext->getId();
        return UserRedis::getRedisInstance()->getNode($userId);
        $select = ['id', 'nickname', 'mobile', 'avatar', 'status', 'intro'];
        return $this->userDao->getOne(['id' => $userId], $select);
    }

    public function updateUserInfo(UserContext $userContext)
    {
        $userId  = $userContext->getId();
        $select  = ['id', 'nickname', 'avatar', 'intro', 'email'];
        $userObj = $this->userDao->findOne($userId, $select);
        if (!$userObj) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('用户不存在'));
        }
        $nickname = request('nickname') ?? '';
        $avatar   = request('avatar') ?? '';
        $email    = request('email') ?? '';
        if (!empty($nickname)) {
            if (mb_strlen($nickname) > 10) {
                throw new ServiceException(ServiceExceptionConstant::getErrorData('昵称不能超过7个字'));
            }
            $userObj->nickname = $nickname;
        }
        if (!empty($avatar)) {
            $userObj->avatar = $avatar;
        }
        if (!empty($email)) {
            $userObj->email = $email;
        }
        $res = $userObj->save();
        if (!$res) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('保存失败'));
        }
        return true;
    }

    public function userCurrentTeam(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $info   = TeamUser::where('user_id', $userId)->where('is_default', 1)->first();
        return ['team_id' => $info ? $info['team_id'] : 0];
    }
}
